from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import subprocess
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

app = FastAPI()

# 从环境变量中读取配置
NGINX_HOME_DIR = os.getenv('NGINX_HOME_DIR', '/opt/soft/nginx')
NGINX_CONF_DIR = os.getenv('NGINX_CONF_DIR', '/opt/soft/nginx/conf/vhost')
NGINX_CONF_FILE = os.getenv('NGINX_CONF_FILE', 'stand.conf.bak')
ANSIBLE_INVENTORY = os.getenv('ANSIBLE_INVENTORY', '/etc/ansible/hosts')
ANSIBLE_PLAYBOOK = os.getenv('ANSIBLE_PLAYBOOK', '/opt/ansible/yamls/switch_nginx.yml')

# 设置 Jinja2 模板目录
templates = Jinja2Templates(directory="templates")

@app.get('/', response_class=HTMLResponse)
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post('/switch_to_maintenance')
async def switch_to_maintenance():
    try:
        subprocess.run(
            [
                'ansible-playbook', ANSIBLE_PLAYBOOK, '-i', ANSIBLE_INVENTORY,
                '-e', f'NGINX_HOME_DIR={NGINX_HOME_DIR}',
                '-e', f'NGINX_CONF_FILE={NGINX_CONF_FILE}',
                '--tags', 'maintenance', '--skip-tags', 'warning'
            ],
            check=True
        )
        logging.info("Switched to Maintenance Mode")
        return {"message": "Switched to Maintenance Mode"}
    except subprocess.CalledProcessError as e:
        logging.error(f"Failed to switch to Maintenance Mode: {e}")
        raise HTTPException(status_code=500, detail="Failed to switch to Maintenance Mode")

@app.post('/switch_to_normal')
async def switch_to_normal():
    try:
        subprocess.run(
            [
                'ansible-playbook', ANSIBLE_PLAYBOOK, '-i', ANSIBLE_INVENTORY,
                '-e', f'NGINX_HOME_DIR={NGINX_HOME_DIR}',
                '-e', f'NGINX_CONF_FILE={NGINX_CONF_FILE}',
                '--tags', 'normal', '--skip-tags', 'warning'
            ],
            check=True
        )
        logging.info("Switched to Normal Mode")
        return {"message": "Switched to Normal Mode"}
    except subprocess.CalledProcessError as e:
        logging.error(f"Failed to switch to Normal Mode: {e}")
        raise HTTPException(status_code=500, detail="Failed to switch to Normal Mode")
if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=5002)
